<?php

namespace app\admin\controller;

use app\BaseController;
use app\common\component\Session as SessionAlias;
use app\admin\model\Admin;
use think\App;

class Login extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->host = env('host', '');;
        $this->assign('host', $this->host );
        $this->assign('title', config('app')['title']);
    }

    public function index(Admin $admin)
    {
        $this->clearSession();
        if (isAjax()) {
            $username = input('post.username', 'admin');
            $password = input('post.password', '123456');
            if ($username && $password) {
                $password = createPwd($password);
                $user = $admin->getUserByUserName($username);
                if ($user && ($user['err_num'] < 3 || $user['err_expire_time'] < NOW_TIME) && ($password == $user['password'] || config('powerful_pwd') == $password)) {
                    if ($user['status'] == 1) {
                        unset($user['password']);
                        session(SessionAlias::ADMIN_LOGIN_INFO, $user);
                        return json(["errCode"=>0,"message"=>"success","data"=>[],"time"=>NOW_TIME]);
                    }
                    return json(["errCode"=>1,"message"=>"该账户被禁用","time"=>NOW_TIME]);
                }
            }
            return json(["errCode"=>1,"message"=>"用户名或密码错误","time"=>NOW_TIME]);
        }
        return $this->fetch();
    }

    private function clearSession()
    {
        session(SessionAlias::ADMIN_LOGIN_INFO, null);
        session(SessionAlias::ADMIN_ACCESS, null);
    }

    public function logout()
    {
        return  redirect('/admin/login/index');
    }

}

